//
// utils.cpp -- Includes implementations of utility functions for string processing, time retrieval, package information lookup, etc.
//

#include "utils.h"
#include "json_utils.h"
#include <algorithm>
#include <cctype>
#include <ctime>

std::string trim(const std::string &str) {
    std::string result = str;
    result.erase(std::remove_if(result.begin(), result.end(), ::isspace), result.end());
    return result;
}

std::string get_current_time() {
    std::time_t now = std::time(nullptr);
    char buf[80];
    std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
    return std::string(buf);
}

std::string find_version_by_name(const std::string &tname, const std::string &file_path) {
    read_package_info(file_path, "packages");
    for (const auto &pkg : packages) {
        if (pkg.name == tname) {
            return pkg.version;
        }
    }
    std::cout << "Package not found: " << tname << std::endl;
    return "";
}

std::string find_package_by_info(const std::string &info, const std::string &file_path) {
    read_package_info(file_path, "packages");
    for (const auto &pkg : packages) {
        if (pkg.info == info) {
            std::cout << "Found package: " << pkg.name << " (" << pkg.version << ")" << std::endl;
            return pkg.name;
        }
    }
    std::cout << "Package not found: " << info << std::endl;
    return "";
}

void print_help() {
    std::cout << "Tiny buildroot packaging tool\n\n";
    std::cout << "Usage: tinybpt <command> [options]\n\n";
    std::cout << "Commands:\n";
    std::cout << "    install <package_name>          Install package\n";
    std::cout << "    uninstall <package_name> [-f]   Uninstall package (use -f to force uninstall)\n";
    std::cout << "    list -all/-installed            List all/installed packages\n";
    std::cout << "    find <package_name>             Find package\n";
    std::cout << "\n";
    std::cout << "Options:\n";
    std::cout << "    -h, -help\n";
    std::cout << "           Show help information\n";
    std::cout << "    -V, -version\n";
    std::cout << "           Show version information\n";
    std::cout << "    -set-mirror <url>               Set mirror URL\n";
    std::cout << "    -get-mirror                     Show mirror URL\n";
}